<template>
  <div class="videoBox" style="width: 100%; height: 100%">
    <video
      id="videoElement"
      ref="myElement"
      :controls="true"
      preload="none"
      autoplay
      muted
    ></video>
  </div>
</template>

<script setup name="videoFlv">
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue"
import flvjs from "flv.js"
import Hls from "hls.js"
import { video } from "../request" // 引入 video axios 实例

const myElement = ref(null)
const props = defineProps({
  flvUrl: {
    default: "",
    type: String
  },
  width: {
    type: String,
    default: "100%"
  },
  height: {
    type: String,
    default: "100%"
  }
})

const url = ref("")
const flvPlayer = ref(null)

const createVideo = async () => {
  const videoElement = myElement?.value
  if (!url.value || !videoElement) {
    console.warn("URL or video element is missing.")
    return
  }

  if (url.value.includes(".m3u8")) {
    if (Hls.isSupported()) {
      const hls = new Hls()
      hls.loadSource(url.value)
      hls.attachMedia(videoElement)
      flvPlayer.value = hls
    } else {
      console.error("HLS is not supported in this browser.")
    }
  } else if (url.value.includes(".flv")) {
    if (flvjs.isSupported()) {
      flvPlayer.value = flvjs.createPlayer(
        {
          type: "flv",
          url: url.value, // 你的url地址
          isLive: true,
          hasAudio: false,
          hasVideo: true, // 数据源是否包含有视频
          enableStashBuffer: false // 是否启用缓存区
        },
        {
          enableWorker: false, // 不启用分离线程
          enableStashBuffer: false, // 关闭IO隐藏缓冲区
          autoCleanupSourceBuffer: true // 自动清除缓存
        }
      )
      flvPlayer.value.attachMediaElement(videoElement)
      flvPlayer.value.load()

      flvPlayer.value.on("error", (error) => {
        console.error("FLV playback error:", error)
        // message.error(`视频加载失败，请稍候重试！`);
        alert(`视频加载失败，请稍候重试！`)
      })

      flvPlayer.value.on("canplay", () => {
        flvPlayer.value.play() // 尝试手动播放
      })
    } else {
      console.error("FLV is not supported in this browser.")
    }
  } else {
    console.warn("Unsupported video format.")
  }
}

const setdestroy = () => {
  flvPlayer.value?.pause()
  flvPlayer.value?.unload()
  flvPlayer.value?.detachMediaElement()
  flvPlayer.value?.destroy()
  flvPlayer.value = null
}

defineExpose({ setdestroy })

onMounted(() => {
  nextTick(() => {
    createVideo()
  })
})

onUnmounted(() => {
  // 确保组件卸载时销毁播放器
  setdestroy()
})

watch(
  () => props.flvUrl,
  (val) => {
    console.log("监听到了摄像头地址", val)
    // 使用 video axios 实例拼接完整的 URL
    url.value = video.defaults.baseURL + val // 假设 val 是相对路径
    if (url.value) {
      console.log("先销毁")
      setdestroy()
      createVideo() // 立即创建视频
    }
  },
  {
    immediate: true,
    deep: true
  }
)
</script>

<style scoped>
#videoElement {
  width: 100%;
  height: 100%;
  object-fit: fill;
}
</style>
